﻿using System.Collections.Generic;
using SharpDX;
using SharpDX.Direct2D1;

namespace FadeGameFramework.UI
{
    public abstract class Control : IUpdatable, IDrawable
    {
        public delegate void MouseEventHandler(MouseEventArgs e);

        protected readonly Bitmap[] BackgroundImageCache = new Bitmap[3];

        private readonly Dictionary<ControlEventState, MouseEventHandler> eventHandlers;

        protected Control() {
            eventHandlers = new Dictionary<ControlEventState, MouseEventHandler> {
                [ControlEventState.MouseDown] = OnMouseDown,
                [ControlEventState.MouseUp] = OnMouseUp,
                [ControlEventState.MouseEnter] = OnMouseEnter,
                [ControlEventState.MouseLeave] = OnMouseLeave
            };
        }

        public Rectangle BoundingRectangle => new Rectangle(Position.X, Position.Y, Size.Width, Size.Height);
        public ControlEventState ControlState { get; private set; } = ControlEventState.Init;
        public string Text { get; set; }
        public Point Position { get; set; }
        public Size2 Size { get; set; }
        public Bitmap Texture { get; set; }
        public int Zorder { get; set; }

        public virtual void Update(float dt) {}

        public event MouseEventHandler OnMouseDown;

        public event MouseEventHandler OnMouseEnter;

        public event MouseEventHandler OnMouseLeave;

        public event MouseEventHandler OnMouseUp;

        public bool Contains(Vector2 point) {
            return BoundingRectangle.Contains(point.X, point.Y);
        }

        public void RaiseEvent(ControlEventState controlState, MouseEventArgs arg) {
            if (ControlState == controlState) return;
            eventHandlers[controlState]?.Invoke(arg);
            ControlState = controlState;
        }
    }
}